package com.sgb.kjwl.view.ui.activity.self.packers;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.tools.ScreenUtils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityWorkteaminfoBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.ShopTeamInfoEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.kjwl.view.ui.adapter.packers.PresonIntroAdapter;
import com.sgb.link.view.widget.ExpandedTextView;
import com.sgb.kjwl.viewmodel.self.packers.WorkTeamInfoModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

/**
 * @author 17389207202
 * @date 2021/3/8
 * description:工队详情（企业）或工队详情（个人）
 */
public class WorkTeamInfoActivity  extends AppActivity {

    private ActivityWorkteaminfoBinding mBind;
    @Inject
    WorkTeamInfoModel viewModel;
    private String mPersonUserNo;
    private String mPersonNo;
    private boolean isCompanyRole;
    private ShopTeamInfoEntity shopTeamData;

    public static final int REQUEST_EDIT_CODE = 100322;

    public static void start(Context context, String no, String userNo) {
        Intent intent = new Intent();
        intent.putExtra("no", no);
        intent.putExtra("userNo", userNo);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(context, WorkTeamInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().
                appComponent(appComponent).selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isCompanyRole){
            mActionBar.setTitle("工队详情（企业）");
        }else {
            mActionBar.setTitle("工队详情（个人）");
        }
    }

    @Override
    protected void initView() {
        mBind = DataBindingUtil.setContentView(this, R.layout.activity_workteaminfo);
        mBind.setViewModel(viewModel);
        // 首选企业编号，如果企业编号为空，则传用户编号，两者不能同时为空，不能同时都有值
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        isCompanyRole = !"".equals(companyNo) && !"0".equals(companyNo);

        mPersonUserNo = getIntent().getStringExtra("userNo");
        mPersonNo = getIntent().getStringExtra("no");
        mBind.edit.setOnClickListener(v -> ActivityJump.jumpToActivityForResult(WorkTeamInfoActivity.this,SelfTeamIntroduceActivity.class,REQUEST_EDIT_CODE, Pair.create("teamType",shopTeamData.getTeamType()+""),Pair.create("no", shopTeamData.getNo())));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_EDIT_CODE) {
                viewModel.getData(mPersonUserNo, mPersonNo,"teamInfo");
            }
        }
    }
    @Override
    protected void init() {
        viewModel.getData(mPersonUserNo, mPersonNo,"teamInfo");
    }

    public void showEmpty() {
        mBind.emptyView.setVisibility(View.VISIBLE);
    }

    public void updateViews(ShopTeamInfoEntity data) {
       this.shopTeamData = data;
        if (data == null) {
            showEmpty();
            return;
        }
        long publishTime = data.getCreateTime();
        if (publishTime > 0) {
            mBind.tvTime.setText(String.format(Locale.CHINA,"%s发布",DateUtils.timestampToDate(publishTime)));
        } else {
            mBind.tvTime.setVisibility(View.INVISIBLE);
        }
        mBind.setViewModeldata(data);
        if (!TextUtils.isEmpty(data.getAvatarAddress())) {
            RoundedCorners roundedCorners = new RoundedCorners(8);
            //通过RequestOptions扩展功能,override采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            RequestOptions options = RequestOptions
                    .bitmapTransform(roundedCorners).override(300, 300)
                    .placeholder(R.mipmap.packer_avatar)
                    .error(R.mipmap.packer_avatar);
            Glide.with(this)
                    .load(data.getAvatarAddress())
                    .apply(options)
                    .into(mBind.shopImg);
        }

        if (!TextUtils.isEmpty(data.getAddress())) {
            mBind.addressLayout.setVisibility(View.VISIBLE);
            String pcA= data.getProvinceName()+data.getCityName()+ data.getAreaName();
            String pc = data.getAreaName();
            //包含省市区
            if (!TextUtils.isEmpty(pcA)&&data.getAddress().contains(pcA)){
                mBind.tvPersonAddress.setText(data.getAddress());
            }else {
                String address;
                if (data.getAddress().contains(pc)){
                    address = data.getAddress().replace(pc,"");
                }else {
                    address = data.getAddress();
                }
                //不包含省市区处理
                mBind.tvPersonAddress.setText(String.format("%s%s",pcA, address ));
            }

        } else {
            mBind.addressLayout.setVisibility(View.GONE);
        }
        switch (data.getTeamType()) {
            case 0:
                mBind.volunteerTeamType.setText("施工队");
                break;
            case 1:
                mBind.volunteerTeamType.setText("班组工队");
                break;
            case 2:
                mBind.volunteerTeamType.setText("承包商");
                break;
            default:
                break;
        }
        if (!TextUtils.isEmpty( data.getCategory())){
            String categoryName = data.getContact();
            if (!TextUtils.isEmpty(categoryName)){
                mBind.tvPersonName.setText(String.format("%s--%s",categoryName,data.getCategory()+mBind.volunteerTeamType.getText().toString()));
            }else {
                mBind.tvPersonName.setText(String.format("%s%s",data.getCategory(),mBind.volunteerTeamType.getText().toString()));
            }
        }
        if (!TextUtils.isEmpty(data.getCategory())) {
            mBind.projectType.setVisibility(View.VISIBLE);
            mBind.projectType.setText(data.getCategory());
        } else {
            mBind.projectType.setVisibility(View.GONE);
        }
        //合作单位布局处理
        //如果没有合作单位那么就隐藏合作单位布局文件，否则显示
        if (data.getTeamType()==0){
            //施工队
            if (!TextUtils.isEmpty(data.getTrustCompanyInfo().getLegalName())){
                mBind.llCooperationCompany.setVisibility(View.VISIBLE);
            }else {
                mBind.llCooperationCompany.setVisibility(View.GONE);
            }
        }else {
            mBind.llCooperationCompany.setVisibility(View.GONE);
        }
        //营业执照
        if (!TextUtils.isEmpty(data.getTrustCompanyInfo().getBusinessLicense())){
            Glide.with(this).load(data.getTrustCompanyInfo().getBusinessLicense()).into(mBind.businessLicense);
        }
        mBind.businessLicense.setOnClickListener(v -> {
            //营业执照放大
            List<String> imageLists = new ArrayList<>();
            imageLists.add(data.getTrustCompanyInfo().getBusinessLicense());
            Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable)imageLists);
            intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, 0);
            getActivity().startActivity(intent);
        });
        //合作协议与委托书处理
        List<String> filePath = data.getTrustCompanyInfo().getFilePath();
        if (filePath!=null&&filePath.size()>0){
            GridLayoutManager manager = new GridLayoutManager( mBind.recyclerview.getContext(), 3);
            mBind.recyclerview.setLayoutManager(manager);
            mBind.recyclerview.addItemDecoration(new GridSpacingItemDecoration(4, ScreenUtils.dip2px(getActivity(), 5), false));
            mBind.recyclerview.setAdapter(new PresonIntroAdapter(mBind.recyclerview.getContext(), filePath));
        }

        mBind.emptyView.setVisibility(View.GONE);

        mBind.tvTeamNum.setText(String.format("%s人",data.getTeamSize()));
        String categoryName = data.getCategoryName();
        if(!TextUtils.isEmpty(categoryName)){
            mBind.tiBusinessText.setText(categoryName.replaceAll(","," | "));
        }else {
            mBind.tiBusinessText.setText("");
        }

        String address = data.getServiceAreaName();
        if (!TextUtils.isEmpty(address)){
            mBind.tvServiceArea.setText(address.replaceAll("、"," | "));
        }
        new ExpandedTextView().showTextT(mBind.tvBasic, mBind.tvBasicExpand);
        new ExpandedTextView().showTextT(mBind.tvHistory, mBind.tvHistoryExpand);
        new ExpandedTextView().showTextT(mBind.tvStructure, mBind.tvStructureExpand);
        new ExpandedTextView().showTextT(mBind.tvIdea, mBind.tvIdeaExpand);
    }
}
